package com.cloudkinto.service.stock.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.ProductStockDao;
import com.cloudkinto.dao.ProductStockRackDao;
import com.cloudkinto.dao.StockCheckDao;
import com.cloudkinto.dao.StockCheckProductDao;
import com.cloudkinto.dto.print.common.DynamicTableDto;
import com.cloudkinto.dto.stock.StockCheckPageDto;
import com.cloudkinto.dto.stock.StockCheckProductDetailDto;
import com.cloudkinto.dto.stock.defective.SkuPickQueryBo;
import com.cloudkinto.dto.stock.defective.SkuStockForPickDto;
import com.cloudkinto.dto.stock.query.SkuCellStockPageDto;
import com.cloudkinto.entity.*;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.enumType.stock.StockOrderTypeEnum;
import com.cloudkinto.enumType.stock.StockTypeEnum;
import com.cloudkinto.enumType.storage.StorageAreaEnum;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.stock.*;
import com.cloudkinto.service.stock.vo.snap.*;
import com.cloudkinto.utils.AsposePdfUtils;
import com.cloudkinto.vo.order.returns.OrProgressRes;
import com.cloudkinto.vo.stock.ProductFlowingInEt;
import com.cloudkinto.vo.stock.ProductFlowingOutEt;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.Cells;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hua
 * @since 2024-12-23
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)//事务回滚
public class StockCheckServiceImpl extends ServiceImpl<StockCheckDao, StockCheckDo> implements StockCheckService {
    private final StockCheckDao dao;
    private final ProductStockDao productStockDao;
    private final StockCheckProductDao stockCheckProductDao;
    private final ProductStockService productStockService;
    private final ProductStockRackDao productStockRackDao;
    private final StockPickingService stockPickingService;
    private final ProductStockFlowingService productStockFlowingService;
    private final OperateRecordService operateRecordService;
    private final StockCheckProductService stockCheckProductService;
    @Value("${gbc.template.localPath}")
    private String localPath;

    @Override
    public List<SkuCellStockPageDto> productListPageByLocation(Map<String, Object> map) {
        List<SkuCellStockPageDto> list = productStockDao.productListPageByLocation(map);
        return list;
    }


    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }


    @Override
    public Object add(StockCheckAddReq req, Long userId, Long whId, Long tenantId) {
        if (req.getPush() == 1) {
            //提交的话 需要锁定库存  且库位不能有锁定库存
            Map<String, Object> map = new HashMap<>();
            map.put("tenantId", tenantId);
            map.put("whId", whId);
            map.put("stockType", 1);//锁定库存
            for (StockCheckProductAddReq product : req.getProducts()) {
                map.put("rackId", product.getRackId());
                map.put("productId", product.getProductId());
                List<SkuCellStockPageDto> skuCellStockPageDtos = productStockDao.productListPageByLocation(map);
                if (!skuCellStockPageDtos.isEmpty()) {
                    throw new BizException("库位：" + skuCellStockPageDtos.get(0).getCellCode() + " 存在锁定库存");
                }
            }
        }
        StockCheckDo entityDo = new StockCheckDo(req.getStockType(), req.getCheckType(), req.getTips());
        entityDo.setWhId(whId);
        //盘点单号
        int count = dao.getCount(tenantId);
        count++;
        StringBuilder returnNo = new StringBuilder(count + "");
        while (returnNo.length() < 4) {
            returnNo.insert(0, 0);
        }
        returnNo.insert(0, DateUtils.dateFormatToString(new Date(), "yyMMdd")).insert(0, "IC");
        entityDo.setOrderNo(returnNo.toString());
        entityDo.setStatus(StaticDict.StockCheck_Status.First.getValue());
        if (req.getPush() == 1) {
            entityDo.setStartTime(new Date());
            entityDo.setStartBy(userId);
            entityDo.setStatus(StaticDict.StockCheck_Status.Second.getValue());
        }
        dao.insert(entityDo);

        for (StockCheckProductAddReq product : req.getProducts()) {
            StockCheckProductDo checkProductDo = new StockCheckProductDo(product.getProductId(), product.getSku(), product.getMainType(), product.getRackId(), product.getCompanyId(), product.getChildTips());
            checkProductDo.setCheckId(entityDo.getId());
            stockCheckProductDao.insert(checkProductDo);
        }
        //提交要锁定库存
        this.lockStock(tenantId, entityDo, req.getPush(), whId);
        operateRecordService.operateAddRecordAndValue("新建", "", entityDo.getId(), userId, null, OperateTypeEnum.StockCheck);

        return entityDo.getId();
    }


    public void lockStock(Long tenantId, StockCheckDo entityDo, int push, Long whId) {
        if (push == 1) {
            //提交了就要锁定库存
            //按照库位优先级，先进先出 获取库存列表
            List<StockPickingDo> pickingList = new ArrayList<>();
            List<StockCheckProductDo> products = stockCheckProductDao.selectList(new LambdaQueryWrapper<StockCheckProductDo>().eq(StockCheckProductDo::getCheckId, entityDo.getId()));
            for (StockCheckProductDo product : products) {
                List<SkuStockForPickDto> stockForPickList = productStockService.getStockForPickList(
                        new SkuPickQueryBo(tenantId, product.getCompanyId(), 1, product.getMainType(), whId, Collections.singletonList(product.getProductId()), Collections.singletonList(product.getRackId())));
                int bookQty = 0;
                for (SkuStockForPickDto i : stockForPickList) {
                    int lockQty = i.getQuantity();
                    if (lockQty == 0) continue;
                    i.setQuantity(0);
                    productStockRackDao.lockStock(i.getStockId(), lockQty);
                    //添加到锁定记录
                    StockPickingDo pickingDo = new StockPickingDo(product.getCompanyId(), whId, entityDo.getId(),
                            StaticDict.Stock_Pick_OrderType.StockCheck.getValue(), "sku", i.getProductId(), i.getRackId(), i.getStockId(), lockQty, null);
                    pickingList.add(pickingDo);
                    bookQty += lockQty;
                }
                product.setBookStock(bookQty);
                stockCheckProductDao.updateById(product);
            }
            stockPickingService.insertBatch(pickingList);
        }
    }

    @Override
    public void start(Long id, Long userId, Long whId, Long tenantId) {
        StockCheckDo entityDo = dao.selectById(id);
        if (!Objects.equals(StaticDict.StockCheck_Status.First.getValue(), entityDo.getStatus())) {
            throw new BizException(SysConstant.No_Data);
        }
        List<StockCheckProductDo> stockCheckProductDos = stockCheckProductDao.selectList(new LambdaQueryWrapper<StockCheckProductDo>().eq(StockCheckProductDo::getCheckId, id));
        List<StockCheckProductUpdateReq> products = BeanConvert.INSTANCE.stockCheckProductUpdateReq(stockCheckProductDos);
        this.checkUpdate(products, entityDo.getWhId(), entityDo.getTenantId());
        this.lockStock(tenantId, entityDo, 1, whId);
        entityDo.setStartTime(new Date());
        entityDo.setStartBy(userId);
        entityDo.setStatus(StaticDict.StockCheck_Status.Second.getValue());
        dao.updateById(entityDo);
        operateRecordService.operateAddRecordAndValue("开始盘点", "", entityDo.getId(), userId, null, OperateTypeEnum.StockCheck);

    }


    @Override
    public void submit(Long id, Long userId, Long whId, Long tenantId) {
        StockCheckDo entityDo = dao.selectById(id);
        if (!Objects.equals(StaticDict.StockCheck_Status.Second.getValue(), entityDo.getStatus())) {
            throw new BizException(SysConstant.No_Data);
        }
        List<StockCheckProductDo> stockCheckProductDos = stockCheckProductDao.selectList(new LambdaQueryWrapper<StockCheckProductDo>().eq(StockCheckProductDo::getCheckId, id));
        for (StockCheckProductDo stockCheckProductDo : stockCheckProductDos) {
            if (stockCheckProductDo.getSolidStock() == null) {
                throw new BizException(SysConstant.StockCheck_NotWrite);
            }
        }
        Map<String, List<StockPickingDo>> pickMap = stockPickingService.lambdaQuery().eq(StockPickingDo::getOrderId, entityDo.getId()).eq(StockPickingDo::getOrderType, StaticDict.Stock_Pick_OrderType.StockCheck.getValue()).list()
                .stream().collect(Collectors.groupingBy(i -> i.getProductId() + "_" + i.getRackId()));
        for (StockCheckProductDo productDo : stockCheckProductDos) {
            this.submitOne(entityDo, productDo, 1, pickMap, userId, whId, tenantId);
        }

        entityDo.setFinishBy(userId);
        entityDo.setFinishTime(new Date());
        entityDo.setStatus(StaticDict.StockCheck_Status.Third.getValue());
        dao.updateById(entityDo);
        operateRecordService.operateAddRecordAndValue("盘点完成", "", entityDo.getId(), userId, null, OperateTypeEnum.StockCheck);

    }


    /**
     * 作废
     */
    @Override
    public void abort(Long id, Long userId, Long whId, Long tenantId) {
        StockCheckDo entityDo = dao.selectById(id);
        if (!Objects.equals(tenantId, entityDo.getTenantId())) return;
        if (!Objects.equals(StaticDict.StockCheck_Status.Second.getValue(), entityDo.getStatus())) {
            throw new BizException(SysConstant.No_Data);
        }
        //回滚锁定库存
        List<StockPickingDo> pickingDos = stockPickingService.lambdaQuery().eq(StockPickingDo::getOrderId, entityDo.getId()).eq(StockPickingDo::getOrderType, StaticDict.Stock_Pick_OrderType.StockCheck.getValue()).list();
        for (StockPickingDo pickingDo : pickingDos) {
            int rollQty = pickingDo.getQuantity();
            int reduce = 0;
            productStockRackDao.updateStock1(pickingDo.getSubStockId(), rollQty, rollQty);
        }
        entityDo.setStatus(StaticDict.StockCheck_Status.Fourth.getValue());
        entityDo.setAbortBy(userId);
        entityDo.setAbortTime(new Date());
        dao.updateById(entityDo);
        operateRecordService.operateAddRecordAndValue("作废", "", entityDo.getId(), userId, null, OperateTypeEnum.StockCheck);

    }


    public void checkUpdate(List<StockCheckProductUpdateReq> products, Long whId, Long tenantId) {
        //提交的话 需要锁定库存  且库位不能有锁定库存
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", tenantId);
        map.put("whId", whId);
        map.put("stockType", 1);//锁定库存
        for (StockCheckProductUpdateReq product : products) {
            map.put("rackId", product.getRackId());
            map.put("productId", product.getProductId());
            List<SkuCellStockPageDto> skuCellStockPageDtos = productStockDao.productListPageByLocation(map);
            if (!skuCellStockPageDtos.isEmpty()) {
                throw new BizException("库位：" + skuCellStockPageDtos.get(0).getCellCode() + " 存在锁定库存");
            }
        }
    }

    @Override
    public Object update(StockCheckUpdateReq req, Long userId, Long whId, Long tenantId) {
        StockCheckDo entityDo = dao.selectById(req.getId());
        if (Objects.equals(StaticDict.StockCheck_Status.First.getValue(), entityDo.getStatus())) {
            //待盘点
            if (req.getPush() == 1) {
                //提交的话 需要锁定库存  且库位不能有锁定库存
                this.checkUpdate(req.getProducts(), whId, tenantId);
                entityDo.setStartTime(new Date());
                entityDo.setStartBy(userId);
                entityDo.setStatus(StaticDict.StockCheck_Status.Second.getValue());
            }
            entityDo.setTips(req.getTips());
            dao.updateById(entityDo);
            stockCheckProductDao.delete(new LambdaQueryWrapper<StockCheckProductDo>().eq(StockCheckProductDo::getCheckId, entityDo.getId()));
            for (StockCheckProductUpdateReq product : req.getProducts()) {
                StockCheckProductDo checkProductDo = new StockCheckProductDo(product.getProductId(), product.getSku(), product.getMainType(), product.getRackId(), product.getCompanyId(), product.getChildTips());
                checkProductDo.setCheckId(entityDo.getId());
                stockCheckProductDao.insert(checkProductDo);
            }
            this.lockStock(tenantId, entityDo, req.getPush(), whId);
            if (req.getPush() == 1) {
                operateRecordService.operateAddRecordAndValue("开始盘点", "", entityDo.getId(), userId, null, OperateTypeEnum.StockCheck);
            }
        } else if (Objects.equals(StaticDict.StockCheck_Status.Second.getValue(), entityDo.getStatus())) {
            for (StockCheckProductUpdateReq product : req.getProducts()) {
                if (product.getSolidStock() == null) {
                    throw new BizException(SysConstant.StockCheck_NotWrite);
                }
            }
            Map<String, List<StockPickingDo>> pickMap = stockPickingService.lambdaQuery().eq(StockPickingDo::getOrderId, entityDo.getId()).eq(StockPickingDo::getOrderType, StaticDict.Stock_Pick_OrderType.StockCheck.getValue()).list()
                    .stream().collect(Collectors.groupingBy(i -> i.getProductId() + "_" + i.getRackId()));
            for (StockCheckProductUpdateReq product : req.getProducts()) {
                StockCheckProductDo productDo = stockCheckProductDao.selectById(product.getId());
                if (productDo == null) continue;
                productDo.setSolidStock(product.getSolidStock());
                productDo.setChildTips(product.getChildTips());
                stockCheckProductDao.updateById(productDo);
                this.submitOne(entityDo, productDo, req.getPush(), pickMap, userId, whId, tenantId);

            }
            if (req.getPush() == 1) {
                entityDo.setFinishBy(userId);
                entityDo.setFinishTime(new Date());
                entityDo.setStatus(StaticDict.StockCheck_Status.Third.getValue());
            }
            entityDo.setTips(req.getTips());
            dao.updateById(entityDo);
            if (req.getPush() == 1) {
                operateRecordService.operateAddRecordAndValue("盘点完成", "", entityDo.getId(), userId, null, OperateTypeEnum.StockCheck);
            }
        } else {
            throw new BizException(SysConstant.No_Data);
        }
        return null;
    }

    public void submitOne(StockCheckDo entityDo, StockCheckProductDo product, int push, Map<String, List<StockPickingDo>> pickMap, Long userId, Long whId, Long tenantId) {
        int quantity = product.getBookStock() - product.getSolidStock();
        if (push == 1) {
            //需要根据差异 调整库存 并解锁库存
            int reduceTotal = 0;
            List<StockPickingDo> pickingDos = pickMap.get(product.getProductId() + "_" + product.getRackId());
            for (StockPickingDo pickingDo : pickingDos) {
                int rollQty = pickingDo.getQuantity();
                int reduce = 0;
                if (quantity > 0) {//需要减少
                    if (quantity <= pickingDo.getQuantity()) {
                        rollQty -= quantity;
                        reduce = quantity;
                        quantity = 0;
                    } else {
                        reduce = rollQty;
                        quantity -= rollQty;
                        rollQty = 0;
                    }
                }
                productStockRackDao.updateStock1(pickingDo.getSubStockId(), rollQty, pickingDo.getQuantity());
                reduceTotal += reduce;
            }
            if (reduceTotal > 0) {
                productStockFlowingService.insertProForOut(ProductFlowingOutEt.builder().sku(product.getSku()).companyId(product.getCompanyId())
                        .warehouseId(whId).rackId(product.getRackId()).stockAttribute(product.getMainType()).tips(product.getChildTips())
                        .bookQuantity(-reduceTotal).orderType(StockOrderTypeEnum.StockCheck.getValue()).noteNo(entityDo.getOrderNo())
                        .tenantId(tenantId).type(StockTypeEnum.one.getValue())
                        .build());
            }
            if (quantity < 0) {//需要新增
                ProductStockDo stockDo = new ProductStockDo(product.getCompanyId(), whId, StockOrderTypeEnum.StockCheck.getValue(), entityDo.getId(), product.getProductId(), Math.abs(quantity), StockTypeEnum.one.getValue(), tenantId);
                productStockDao.insert(stockDo);
                ProductStockRackDo rackDo = new ProductStockRackDo(stockDo.getId(), product.getRackId(), product.getMainType(), Math.abs(quantity), Math.abs(quantity));
                productStockRackDao.insert(rackDo);
                //库存流水
                productStockFlowingService.insertProForIn(ProductFlowingInEt.builder().sku(product.getSku()).companyId(product.getCompanyId())
                        .warehouseId(whId).rackId(product.getRackId()).stockAttribute(rackDo.getStockAttribute())
                        .bookQuantity(stockDo.getReceiveQuantity()).orderType(StockOrderTypeEnum.StockCheck.getValue()).noteNo(entityDo.getOrderNo()).tips(product.getChildTips())
                        .tenantId(tenantId).type(StockTypeEnum.one.getValue())
                        .build());
            }

        }
    }


    @Override
    public int delete(Long id, Long userId) {
        StockCheckDo entityDo = dao.selectById(id);
        if (!Objects.equals(StaticDict.StockCheck_Status.First.getValue(), entityDo.getStatus())) {
            throw new BizException(SysConstant.NoPower);
        }
        return dao.deleteById(id);
    }

    public List<OrProgressRes> setProgressList(StockCheckDetailRes res) {
        List<OrProgressRes> progressList = new ArrayList<>();
        progressList.add(new OrProgressRes("create", "创建", res.getOrderNo(), res.getCreateTime(), res.getCreateByName()));
        progressList.add(new OrProgressRes("start", "开始盘点", res.getOrderNo(), res.getStartTime(), res.getStartByName()));
        if (StaticDict.StockCheck_Status.Fourth.getValue().equals(res.getStatus())) {
            progressList.add(new OrProgressRes("abort", "作废", res.getOrderNo(), res.getAbortTime(), res.getAbortByName()));
        } else {
            progressList.add(new OrProgressRes("complete", "盘点完成", res.getOrderNo(), res.getFinishTime(), res.getFinishByName()));
        }
        return progressList;
    }


    @Override
    public Object detail(Long id, Long whId, Long tenantId) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("whId", whId);
        map.put("tenantId", tenantId);
        List<StockCheckPageDto> list = dao.list(map);
        if (list.isEmpty()) return null;
        StockCheckDetailRes res = new StockCheckDetailRes();
        BeanUtils.copyProperties(list.get(0), res);
        res.setOperateResList(operateRecordService.getOperateList(id, OperateTypeEnum.StockCheck));
        res.setProgress(this.setProgressList(res));
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        Map<String, Object> result = new HashMap<>();
        List<Map<Object, Object>> stockCheckStatus = StaticDict.getStockCheck_Status();
        Map<Object, Object> map = new HashMap<>();
        map.put("id", null);
        map.put("name", "全部");
        stockCheckStatus.add(0, map);
        result.put("status", stockCheckStatus);
        //库存类型
        result.put("storageArea", StorageAreaEnum.getMapList());
        return SingleResult.success(result);
    }

    @Override
    public List<StockCheckPageDto> getList(Map<String, Object> map) {
        List<StockCheckPageDto> list = dao.list(map);
        return list;
    }

    @Override
    public PageResult getListPage(Map<String, Object> map) {
        IPage<StockCheckPageDto> page = pageInit(map);
        page = dao.list(page, map);
        PageResult result = new PageResult(page.getRecords(), (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    private IPage<StockCheckPageDto> pageInit(Map<String, Object> map) {
        IPage<StockCheckPageDto> page = new Page();
        page.setSize(map.get("pageSize") == null ? Long.parseLong(map.get("pageSize").toString()) : 10);
        page.setCurrent(map.get("current") == null ? Long.parseLong(map.get("current").toString()) : 1);
        return page;
    }


    @Override
    public List<Map<String, Object>> statusStatistics(Map<String, Object> map) {
        map.remove("status");
        Map<Integer, List<StockCheckPageDto>> collect = dao.list(map).stream().collect(Collectors.groupingBy(StockCheckPageDto::getStatus));
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (StaticDict.StockCheck_Status value : StaticDict.StockCheck_Status.values()) {
            Map<String, Object> m = new HashMap<>();
            m.put("id", value.getValue());
            m.put("name", value.getText());
            m.put("sum", collect.get(value.getValue()) == null ? 0 : collect.get(value.getValue()).size());
            resultList.add(m);
        }
        return resultList;
    }

    @Override
    public void printCheckList(Map<String, Object> map, HttpServletResponse response) throws Exception {
        List<StockCheckPageDto> list = dao.list(map);
        if (list.isEmpty()) throw new BizException(SysConstant.No_Data);
        StockCheckPageDto entityDo = list.get(0);
        List<StockCheckProductDetailDto> productList = stockCheckProductService.getList(entityDo.getId());

        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;filename=shelfPrint.pdf");
        //通用参数
//        byte[] pasNoBarcode = BarCodeUtils.generateBarCode128(
//                entityDo.getOrderNo(), false, false, 256, 15, 0.3f, 0f, 0f
//        );
//        ByteArrayInputStream pasNoBarcodeImg = new ByteArrayInputStream(pasNoBarcode);
        Map<String, Object> data = new HashMap<>(16);
        data.put("orderNo", entityDo.getOrderNo());
        data.put("whCode", entityDo.getWhCode());
        data.put("createByName", entityDo.getCreateByName());
        data.put("checkType", 1 == entityDo.getCheckType() ? "库位盘点" : "sku+库位盘点");
        data.put("printTime", DateUtil.date());
//        data.put("defectiveNoBarcode", Pictures.ofStream(pasNoBarcodeImg, PictureType.PNG).size(245, 70).create());
        data.put("tips", entityDo.getTips());
        data.put("status", StaticDict.StockCheck_Status.getText(entityDo.getStatus()));
        List<StockCheckTableDto> checkList = new ArrayList<>();
        AtomicInteger i = new AtomicInteger(1);
        for (StockCheckProductDetailDto productDto : productList) {
            checkList.add(new StockCheckTableDto(String.valueOf(i.getAndIncrement()), productDto.getSkuSimple(),
                    productDto.getProductName(), productDto.getCellNo(), StorageAreaEnum.getAreaTypeName(productDto.getAreaType()),
                    productDto.getBookStock() == null ? "-" : productDto.getBookStock() + "", productDto.getSolidStock() == null ? "-" : productDto.getSolidStock() + "", productDto.getChildTips()));
        }
        data.put("list", checkList);
        ConfigureBuilder configureBuilder = Configure.builder();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ServletOutputStream out = response.getOutputStream();
        //获取模板文件
        File templateFile = new File(localPath + File.separator + "stockCheck-list.docx");
        //模板配置
        configureBuilder.bind("list", new LoopRowTableRenderPolicy());
        XWPFTemplate template = XWPFTemplate.compile(templateFile, configureBuilder.build()).render(data);
        template.writeAndClose(bos);
        //转换为pdf
        ByteArrayOutputStream pdf = AsposePdfUtils.word2pdf(new ByteArrayInputStream(bos.toByteArray()));
        out.write(pdf.toByteArray());
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out, pdf);
    }

    private DynamicTableDto getStockCheckPrintTableData(List<StockCheckTableDto> dtoList, DynamicTableDto dynamicTableDto) {
        for (StockCheckTableDto dto : dtoList) {
//            dynamicTableDto.getGroupMap().put(dto.getNo(), dto.getSonList().size());
//            byte[] boxBarcode = BarCodeUtils.generateBarCode128(dto.getSku(), false, false, 256, 15, 0.4f, 0, 0);
//            ByteArrayInputStream boxBarcodeImg = new ByteArrayInputStream(boxBarcode);
            RowRenderData rowRenderData = Rows.of(
                    Cells.of(dto.getNo()).create(),
                    Cells.of(dto.getSku()).create(),
//                        Cells.of(Pictures.ofStream(boxBarcodeImg, PictureType.PNG).size(190, 55).create()).create(),
                    Cells.of(dto.getProductName()).create(),
                    Cells.of(dto.getCellNo()).create(),
                    Cells.of(dto.getAreaType()).create(),
                    Cells.of(dto.getBookStock() == null ? "-" : String.valueOf(dto.getBookStock())).create(),
                    Cells.of(dto.getSolidStock() == null ? "-" : String.valueOf(dto.getSolidStock())).create(),
                    Cells.of(dto.getChildTips()).create()
            ).center().create();
            dynamicTableDto.getDataList().add(rowRenderData);
            for (Map<String, String> sonMap : dto.getSonList()) {

            }
        }
        return dynamicTableDto;
    }

}
